#!/bin/bash
# Copyright (c) The Libra Core Contributors
# SPDX-License-Identifier: Apache-2.0
set -e

# Different versions of cti script have different name for this, will eventually get rid of REMOTE_USER
MARKER=${CTI_MARKER:-${REMOTE_USER}}

CONF_FILE=$(readlink -f $0).conf
[[ -f "$CONF_FILE" ]] && source "$CONF_FILE"
# This will allow to block(gate) certain --marker
# Config file should be in same directory as this shell script and has suffix .conf
# For example if this script is located in /usr/local/bin/ct, then config file is /usr/local/bin/ct.conf
# Example of config file:
#    RET_land=0 # do not run cluster test and return success for land jobs
#    RET_nightly=1 # do not run cluster test and return failure for nightly jobs
#    RET_user-x=1 # do not run cluster test and return failure for user user-x
CONF_NAME=RET_$MARKER
CONF_VALUE="${!CONF_NAME}"
if [ ! -z "${CONF_VALUE}" ]; then
    echo "Config ${CONF_NAME} is set to ${CONF_VALUE}, will use this as exit code and terminate"
    exit ${CONF_VALUE}
fi

echo "$(TZ='America/Los_Angeles' date) [${MARKER}] $*" >> ~/ct.log

DOCKER_IMAGE=""
WAIT_TO="45m"
export CONTAINER="cluster-test-$RANDOM"
LOCAL_LATEST_IMAGE="cluster-test:latest"
MASTER_IMAGE="853397791086.dkr.ecr.us-west-2.amazonaws.com/libra_cluster_test:master"

while (( "$#" )); do
  case "$1" in
    -c|--container)
      export CONTAINER=$2
      shift 2
      ;;
    -P|--prune)
      docker image prune -a -f
      shift 1
      ;;
    -i|--image)
      DOCKER_IMAGE=$2
      shift 2
      ;;
    -T|--wait-timeout)
      WAIT_TO=$2
      shift 2
      ;;
    -L|--latest)
      DOCKER_IMAGE="${LOCAL_LATEST_IMAGE}"
      shift 1
      ;;
    --) # end argument parsing
      shift
      break
      ;;
    *) # end argument parsing
      break
      ;;
  esac
done

# Only pull when not using the local image
if [ "${DOCKER_IMAGE}" != "${LOCAL_LATEST_IMAGE}" ]; then
  if [ -z "${DOCKER_IMAGE}" ]; then
    DOCKER_IMAGE="${MASTER_IMAGE}"
  fi
  $(aws ecr get-login --no-include-email --region us-west-2)
  docker pull "${DOCKER_IMAGE}"
fi

echo "Using $DOCKER_IMAGE image for cluster-test"

# Waiting for other runs to finish
timeout $WAIT_TO bash -c 'while [ $(docker ps --quiet --filter name=$CONTAINER) ]; do echo "Another container is running, waiting..."; sleep 1m; done'

# Cleanup container in case it was terminated but not removed (no -f flags to avoid killing alive container)
docker rm $CONTAINER 2>/dev/null >/dev/null || :

trap "echo Terminating on SIGINT; docker rm -f $CONTAINER >/dev/null" SIGINT
trap "echo Terminating on SIGTERM; docker rm -f $CONTAINER >/dev/null" SIGTERM
trap "echo Terminating on SIGHUP; docker rm -f $CONTAINER >/dev/null" SIGHUP

VARS="-e RUST_LOG -e VERBOSE -e RUST_BACKTRACE -e SLACK_CHANGELOG_URL"

# This could in theory fail due to concurrency, but it seem unlikely
docker run --ulimit nofile=98304:98304 $VARS -v /libra_rsa:/libra_rsa --name $CONTAINER --rm $DOCKER_IMAGE $* &

wait $!
